package com.chat.datea.fragment;

import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.chat.datea.R;
import com.chat.datea.adapter.MusicRecomFragment_GridView_Adapter;
import com.chat.datea.adapter.MusicRecomFragment_ListView_Adapter;
import com.chat.datea.adapter.MusicRecomFragment_ViewPager_Adapter;
import com.chat.datea.base.BaseFragment;
import com.chat.datea.base.Finnal_Base;
import com.chat.datea.bean.MusicList;
import com.chat.datea.bean.RecomHotMusicEntivity;
import com.chat.datea.bean.RecomNewsMusicEntivity;
import com.chat.datea.bean.RecomNewsToDayMusicEntivity;
import com.chat.datea.bean.RecomTopViewPagerEntivity;
import com.chat.datea.bean.UserRecEntivity;
import com.chat.datea.bean.UserRecTopEntivity;
import com.chat.datea.ui.MainActivity;
import com.chat.datea.utils.fragment.ReplaceFragment;
import com.chat.datea.utils.listview_for_scrollview.ListViewForScrollView;
import com.chat.datea.utils.volley.VolleySingleton;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by xyb on 15/10/20.
 */
public class MusicRecomFragment extends BaseFragment implements View.OnClickListener {
    private FragmentManager fManager;
    private ScrollView sv;
    private GridView gridView;
    private ViewPager recomViewPager;
    private VolleySingleton singleton;
    private ImageView singer_img, today_one, today_two, today_three, img_press, today_img_press;
    private TextView singer_name, today_name, more;
    private Handler handler = new Handler();
    private MusicRecomFragment_ViewPager_Adapter pagerAdapter;
    private MusicRecomFragment_GridView_Adapter viewAdapter;
    private MusicRecomFragment_ListView_Adapter listViewAdapter;
    private List<RecomTopViewPagerEntivity.PicEntity> pic;
    private ListViewForScrollView forScrollView;
    private List<UserRecEntivity.ResultEntity.ListEntity> list;
    private List<RecomHotMusicEntivity.ContentEntity.SongListEntity> content;
    private List<RecomNewsMusicEntivity.PlazeAlbumListEntity.RMEntity.AlbumListEntity.ListEntity> listEntities;
    private RecomNewsToDayMusicEntivity.CollectionEntity entity;
    private String dayNum;
    private String num;

    public MusicRecomFragment(FragmentManager fManager) {
        this.fManager = fManager;


    }

    @Override
    protected void initData() {
        more.setOnClickListener(this);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.add(calendar.DATE, 0);
        String newsDate = sdf.format(calendar.getTime());
        SimpleDateFormat dd = new SimpleDateFormat("dd");
        dayNum = dd.format(calendar.getTime());
            num = dayNum.substring(1, 2);
        today_name.setText("今日歌单 " + newsDate);
        singleton = VolleySingleton.getVolleySingleton(mActivity);
        viewAdapter = new MusicRecomFragment_GridView_Adapter(mActivity, fManager);
        gridView.setAdapter(viewAdapter);
        initViewPagerData();
        initListViewData();
        initGridViewData();
        initViewData(num);// 今日推荐


    }

    /**
     * 今日推荐
     */
    private void initViewData(String num) {
        int today = 0;
        if (num.equals("0")) {
            today = 0;
        } else if (num.equals("1")) {
            today = 1;
        } else if (num.equals("2")) {
            today = 2;
        } else if (num.equals("3")) {
            today = 3;
        } else if (num.equals("4")) {
            today = 4;
        } else if (num.equals("5")) {
            today = 5;
        } else if (num.equals("6")) {
            today = 6;
        } else if (num.equals("7")) {
            today = 7;
        } else if (num.equals("8")) {
            today = 8;
        } else if (num.equals("9")) {
            today = 9;
        }

        final int finalToday = today;
        final StringRequest request = new StringRequest(Finnal_Base.userRec, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                UserRecEntivity userRecEntivity = gson.fromJson(response, UserRecEntivity.class);
                if (userRecEntivity != null) {
                    list = new ArrayList<>();
                    list = userRecEntivity.getResult().getList();
                   if (list != null && list.size() > 0){
                       singer_name.setText(list.get(finalToday).getName());
                       Picasso.with(mActivity).load(list.get(finalToday).getAvatar_big()).into(singer_img);
                       gotoGuessSingerFragment(finalToday);
                   }
                }
                // 猜你喜欢

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        request.setShouldCache(false);

        StringRequest stringRequest = new StringRequest(Finnal_Base.userRecTop, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                UserRecTopEntivity topEntivity = gson.fromJson(response, UserRecTopEntivity.class);
                topEntivity.getResult().getList();
                for (int i = 0; i < topEntivity.getResult().getList().size(); i++) {
                    switch (i) {
                        case 0:
                            try {
                                Picasso.with(mActivity).load(topEntivity.getResult().getList().get(0).getPic_big()).into(today_one);
                            } catch (Exception e) {

                            }
                            break;
                        case 1:
                            try {
                                Picasso.with(mActivity).load(topEntivity.getResult().getList().get(1).getPic_big()).into(today_two);
                            } catch (Exception e) {

                            }
                            break;
                        case 2:
                            try {
                                Picasso.with(mActivity).load(topEntivity.getResult().getList().get(2).getPic_big()).into(today_three);
                            } catch (Exception e) {

                            }
                            break;
                    }
                }
                gotoEveryDayFragment();


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        singleton.addQueue(stringRequest, "MusicRecomFragment");
        singleton.addQueue(request, "MusicRecomFragment");


    }

    private void gotoEveryDayFragment() {

        today_img_press.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EveryDayFragment everyDayFragment = new EveryDayFragment(dayNum);
                new ReplaceFragment(everyDayFragment, fManager, R.id.fl_content, true, null);

            }
        });

    }

    /**
     * 点击今日推荐的歌手跳到歌手的详情页面
     */
    private void gotoGuessSingerFragment(final int finalToday) {

        img_press.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String ting_uid = list.get(finalToday).getTing_uid();
                String artist_id = list.get(finalToday).getArtist_id();
                String sing_name = list.get(finalToday).getName();
                GuessSingerFragment guessSingerFragment = new GuessSingerFragment(fManager, ting_uid, artist_id, sing_name);
                new ReplaceFragment(guessSingerFragment, fManager, R.id.fl_content, true, null);
            }
        });

    }

    private void initGridViewData() {
        StringRequest request = new StringRequest(Finnal_Base.todayNewsMusicUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                RecomNewsToDayMusicEntivity musicEntivity = gson.fromJson(response, RecomNewsToDayMusicEntivity.class);
                entity = musicEntivity.getCollection();
                viewAdapter.addTodayData(entity);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        StringRequest stringRequest = new StringRequest(Finnal_Base.newsMusicUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                RecomNewsMusicEntivity entivity = gson.fromJson(response, RecomNewsMusicEntivity.class);
                listEntities = entivity.getPlaze_album_list().getRM().getAlbum_list().getList();
                viewAdapter.addNewsData(listEntities);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        singleton.addQueue(request, "MusicRecomFragment");
        singleton.addQueue(stringRequest, "MusicRecomFragment");

    }

    private void initListViewData() {
        StringRequest request = new StringRequest(Finnal_Base.ListUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                RecomHotMusicEntivity musicEntivity = gson.fromJson(response, RecomHotMusicEntivity.class);
                content = musicEntivity.getContent().get(0).getSong_list();
                listViewAdapter = new MusicRecomFragment_ListView_Adapter(mActivity, content);

                forScrollView.setAdapter(listViewAdapter);
                forScrollView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        ArrayList<MusicList> lists = new ArrayList<>();
                        for (RecomHotMusicEntivity.ContentEntity.SongListEntity listEntity : content) {
                            MusicList musicList = new MusicList();
                            musicList.setName(listEntity.getTitle());
                            musicList.setSinger(listEntity.getAuthor());
                            musicList.setSongId(listEntity.getSong_id());
                            musicList.setFrom("网络");
                            lists.add(musicList);
                        }

                        MainActivity.play(lists, position);
                        Toast.makeText(mActivity, "请稍候!音乐正在路上", Toast.LENGTH_SHORT).show();
                    }
                });

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        singleton.addQueue(request, "MusicRecomFragment");
    }

    private void initViewPagerData() {
        StringRequest request = new StringRequest(Finnal_Base.Url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                RecomTopViewPagerEntivity pagerEntivity = gson.fromJson(response, RecomTopViewPagerEntivity.class);
                pic = pagerEntivity.getPic();
                pagerAdapter = new MusicRecomFragment_ViewPager_Adapter(mActivity, pic);
                recomViewPager.setAdapter(pagerAdapter);
                handler.postDelayed(runnable, 4000);// 开启线程
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        singleton.addQueue(request, "MusicRecomFragment");

    }

    @Override
    protected void initView() {
        recomViewPager = (ViewPager) view.findViewById(R.id.recomViewPager);
        gridView = (GridView) view.findViewById(R.id.everyDay_img);
        forScrollView = (ListViewForScrollView) view.findViewById(R.id.sunMusic);
        singer_img = (ImageView) view.findViewById(R.id.singer_img);
        singer_name = (TextView) view.findViewById(R.id.singer_name);
        more = (TextView) view.findViewById(R.id.more);
        today_name = (TextView) view.findViewById(R.id.today_name);
        today_one = (ImageView) view.findViewById(R.id.today_one);
        today_two = (ImageView) view.findViewById(R.id.today_two);
        today_three = (ImageView) view.findViewById(R.id.today_three);
        img_press = (ImageView) view.findViewById(R.id.img_press);
        today_img_press = (ImageView) view.findViewById(R.id.today_img_press);
        sv = (ScrollView) view.findViewById(R.id.sv);
        sv.smoothScrollTo(0, 0);// 手动将scrol滑动到顶部
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container) {
        view = inflater.inflate(R.layout.fragment_recom, null);
        return view;
    }


    // 轮播线程
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            int index = recomViewPager.getCurrentItem();
            recomViewPager.setCurrentItem(++index);
            handler.postDelayed(runnable, 4000);
        }
    };

    @Override
    public void onPause() {
        super.onPause();
        handler.removeCallbacks(runnable);
        singleton.removeRequest("MusicRecomFragment");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.more:
                NewMusicFragment newMusicFragment = new NewMusicFragment();
                new ReplaceFragment(newMusicFragment, getActivity().getSupportFragmentManager(), R.id.fl_content, true, null);
                break;
        }
    }
}
